//
//  LoginViewModel.swift
//  AESOLAR_IOS
//
//  Created by Mac on 2019/8/22.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

struct LoginViewModel: ViewModelType {
    
    let id: String?
    
    struct Input {
        let email: ControlProperty<String?>
        let code: ControlProperty<String?>
        let getCodeTap: ControlEvent<Void>
        let loginTap: ControlEvent<Void>
    }
    
    struct Output {
        let codeButtonState: Observable<(title: String, isEnabled: Bool)>
        let loginResult: Observable<LoginModel?>
    }
    
    func transform(_ input: LoginViewModel.Input) -> LoginViewModel.Output {
        
        let codeButtonState = input.getCodeTap.withLatestFrom(input.email.orEmpty)
            .filter{ $0.checkAvailable("请输入邮箱".localized) &&
                $0.checkAvailable("邮箱格式不正确".localized, closure: { $0.isEmail })
        }.flatMap {
                // 获取验证码
                ApiManager.getCode($0).request()
                    .errorWhenCodeNot200()
                    .map{ $0.isSuccess }
                    .trackingLoading()
                    .catchErrorJustReturn(false)
        }.flatMapFirst { success -> Observable<(title: String, isEnabled: Bool)> in
            if success {
                return 60.countdown({ String.init(format: "%d 秒后重新获取".localized, $0) },
                                    resend: "重新发送验证码".localized)
            } else {
                return Observable.just((title: "重新发送验证码".localized, isEnabled: true))
            }
        }.share(replay: 1)
        
        let loginInput = Observable.combineLatest(input.email.orEmpty, input.code.orEmpty)
        
        let loginResult = input.loginTap.withLatestFrom(loginInput)
            .filter{ $0.0.checkAvailable("请输入邮箱".localized) && $0.1.checkAvailable("请输入验证码".localized) &&
                $0.0.checkAvailable("邮箱格式不正确".localized, closure: { $0.isEmail }) &&
                $0.0.checkAccountExists("该账号已删除！".localized)}
            .flatMapFirst{
                
//                LoginAccountInfo.isAccountExists($0.0);
//                let ret: Bool = LoginAccountInfo.isAccountExists($0.0);
//                if ret == false {
//                    
//                    
//                }
                
                ApiManager.login(email: $0.0, vcode: $0.1, subAccount: self.id)
                    .request()
                    .trackingLoading()
                    .errorWhenCodeNot200()
                    .dataModelMap(LoginModel.self)
                    .mapOptional()
                    .catchErrorJustReturn(nil)
        }
        
        return Output(codeButtonState: codeButtonState, loginResult: loginResult)
    }
    
}
